import type { Router } from 'vue-router';

import NProgress from 'nprogress';
import { useUserStore } from '@/settings/stores';
import { isLoginForClient, gotoLoginForClient } from '@/common/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async () => {
    const userStore = useUserStore();

    if (isLoginForClient()) {
      if (userStore.user.id) {
        return true;
      }
      else {
        const { isSuccess } = await userStore.fetchInfo();

        if (!isSuccess) {
          NProgress.done();

          // 登录有效但是取不出来用户信息，说明不能登录后台，跳转到 404
          location.replace('/404');

          return false;
        }

        return isSuccess;
      }
    }
    else {
      NProgress.done();

      gotoLoginForClient();

      return false;
    }
  });
}
